
import 'package:grasp_flutter_app/utils/model/user.dart';

import '../utils.dart';

/// 用户数据存取对象
class UserDao {

  static login(userName, password, store) async {
    await LocalStorage.save(Config.USER_NAME_KEY, userName);
    await getUserInfo(userName);
    store.dispatch(new UpdateUserAction(new User({"name" : userName})));
  }

  ///初始化用户信息
  static Future<User> initUserInfo(Store store) async {
    var res = await getUserInfoLocal();
    if (res != null) {
      store.dispatch(UpdateUserAction(res));
    }

    ///读取主题
    String themeIndex = await LocalStorage.get(Config.THEME_COLOR);
    if (themeIndex != null && themeIndex.length != 0) {
      Utils.pushTheme(store, int.parse(themeIndex));
    }

    ///切换语言
    String localeIndex = await LocalStorage.get(Config.LOCALE);
    if (localeIndex != null && localeIndex.length != 0) {
      Utils.changeLocale(store, int.parse(localeIndex));
    } else {
      Utils.curLocale = store.state.platformLocale;
      store.dispatch(RefreshLocaleAction(store.state.platformLocale));
    }

    return res;
  }

  ///获取用户详细信息
  static getUserInfo(userName, {needDb = false}) async {
    await LocalStorage.save(Config.USER_INFO, Utils.jsonToString({"name" : userName}));
  }

  static clearAll(Store store) async {
    HttpManager.clearAuthorization();
    LocalStorage.remove(Config.USER_INFO);
    store.dispatch(new UpdateUserAction(User.empty()));
  }

  ///获取本地登录用户信息
  static Future<User> getUserInfoLocal() async {
    var userText = await LocalStorage.get(Config.USER_INFO);
    print(userText);
    if (userText != null) {
      return User(Utils.parseJson(userText));
    } else
      return null;
  }

}

class UpdateUserAction {
  final User userInfo;
  UpdateUserAction(this.userInfo);
}